import { Log } from './log';

export const ref = {
  count: 0
}

function onFinishReq() {
  ref.count--;
}

// 统计 xhr 耗时
export function initXhr(ctx) {
  const MXMLHttpRequest = window.XMLHttpRequest;

  window.XMLHttpRequest = function (...arg) {
    ref.count++;

    const request = new MXMLHttpRequest(...arg);

    let url = "";

    /**
     * 这里代理 open，是为了获取请求 url
     * 否则在 error 事件处理器中无法得到 responseURL
     */
    let open = request.open;
    request.open = function (...arg) {
      url = arg[1];
      open.call(request, ...arg)
    }

    const start_time = Date.now();

    /**
     * 请求已经完成
     * 服务端可能响应 2xx 3xx 4xx 5xx 等等
     */
    request.addEventListener('load', function (e) {
      onFinishReq();

      const xmlhttp = e.target;
      const end_time = Date.now();
  
      Log.log(`xhr load ${url} use ${end_time - start_time}ms`);

      ctx.sendXhrEvent({
        start_time: start_time,
        end_time: end_time,
        spend_time: end_time - start_time,
        url: url,
        http_code: xmlhttp.status // 200
      })
    })

    /**
     * 请求没有得到处理
     * 可能是服务器挂了
     */
    request.addEventListener('error', function(e) {
      onFinishReq();

      Log.log(`xhr error ${url}`);

      const xmlhttp = e.target;
      const end_time = Date.now();

      ctx.sendXhrEvent({
        start_time: start_time,
        end_time: end_time,
        spend_time: end_time - start_time,
        url: url,
        http_code: xmlhttp.status // 0
      })
    })

    return request;
  }
}
